<template>
  <div>
    <van-cell v-for="item in suggEstions" :key="item" icon="search">
      <template #title>
        <div v-html="haghIext(item)" @click="onSearch(item)"></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
export default {
  data () {
    return {
      suggEstions: []
    }
  },
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  beforeDestroy () {
    clearTimeout(this.setid)
  },
  watch: {
    searchText: {
      // 开启深度侦听
      immediate: true,
      handler (newVal) {
        if (this.setid) {
          clearTimeout(this.setid)
        }
        this.setid = setTimeout(async () => {
          const res = await getSearchSuggestion(newVal)
          this.suggEstions = res.options
        }, 700)
      }
    }
  },
  created () {

  },

  methods: {
    // 高亮
    haghIext (item) {
      const repLaceStr = '<span style="color: red">' + this.searchText + ' </span>'
      const reg = new RegExp(this.searchText, 'gi')
      return item.replace(reg, repLaceStr)
    },
    // 底部推荐传入输入框
    onSearch (item) {
      this.$emit('onSearch', item)
    }
  }
}
</script>

<style scoped lang='less'>

</style>
